package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;


// 收货地址
@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    //查看所有地址
    @Override
    public List<Address> list() {
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());
        List<Address> addresses = addressMapper.selectList(qw);
        return addresses;
    }

    //新增地址
    @Override
    public void add(Address address) {
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0); // 是否默认地址
        addressMapper.insert(address);
    }

    //修改默认地址
    @Override
    public void setDefault(Address newDefault) {
        Address address = new Address();
        address.setIsDefault(0);

        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        addressMapper.update(address,qw);

        newDefault.setIsDefault(1);
        addressMapper.updateById(newDefault);

    }

    //查询默认地址
    @Override
    public Address findDefault() {
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getIsDefault,1);
        return addressMapper.selectOne(qw);
    }

    //ID回显地址
    @Override
    public Address getDetail(Long id) {
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getId,id);
        return addressMapper.selectOne(qw);
    }

    //修改
    @Override
    public void update(Address address) {
        addressMapper.updateById(address);
    }





}
